#include "ota_runner.h"
#include "ota_http.h"
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/reboot.h>
#include <assert.h>
#include "log/log.h"

static int ota_runner_canUpdate(Version *ver)
{
    if (ver->major > VER_MAJOR)
    {
        return 0;
    }
    if (ver->major == VER_MAJOR && ver->minor > VER_MINOR)
    {
        return 0;
    }
    if (ver->major == VER_MAJOR && ver->minor == VER_MINOR && ver->patch > VER_PATCH)
    {
        return 0;
    }
    return -1;
}

static void ota_runner_signalHandler(int sig)
{
    assert(sig == SIGTERM);
    exit(0);
}

void ota_runner_run(void)
{
    // 注册终止信号
    signal(SIGTERM, ota_runner_signalHandler);

    while (1)
    {
        Version *ver = ota_http_getVersion();
        if (!ver)
        {
            log_warn("get version failed");
            sleep(60);
            continue;
        }
        log_info("current version: %d.%d.%d", VER_MAJOR, VER_MINOR, VER_PATCH);
        log_info("latest version: %d.%d.%d", ver->major, ver->minor, ver->patch);
        if (ota_runner_canUpdate(ver) < 0)
        {
            // 无版本更新
            log_info("no new version");
            sleep(86400);
            continue;
        }

        // 可以更新，尝试下载固件
        if (ota_http_getFirmware(FW_PATH) < 0)
        {
            log_warn("get firmware failed");
            sleep(3600);
            continue;
        }

        log_info("get firmware success, rebooting...");
        sleep(5);

        // 下载固件成功, 直接重启
        reboot(RB_AUTOBOOT);
    }
}